class Game {
    constructor(){
        this.sky = new Sky();
        this.land = new Land(-100);
        this.bird = new Bird();
        this.pipeProducer = new PipeCreat(-100);
        this.tick = 16;
        this.timer = null;
        this.gameover = false;
    }

    start(){
        if(this.timer){
            return;
        }
        if(this.gameover){
            window.location.reload();
        }
        this.pipeProducer.starProduce();
        this.bird.starSW();
        this.timer = setInterval(() => {
            const atime = this.tick/1000;
            this.sky.move(atime);
            this.land.move(atime);
            this.bird.move(atime);
            this.pipeProducer.pairs.forEach(pair => {
                pair.move(atime);
            });
            if(this.isGameOver()){
                this.stop();
                this.gameover = true;
            }
            
        }, this.tick);

    }

    isHit(rec1,rec2){
        var centerX1 = rec1.left + rec1.width / 2;
        var centerY1 = rec1.top + rec1.height / 2;
        var centerX2 = rec2.left + rec2.width / 2;
        var centerY2 = rec2.top + rec2.height / 2;
        var disX = Math.abs(centerX1 - centerX2);
        var disY = Math.abs(centerY1 - centerY2);
        if(disX <(rec1.width + rec2.width)/2 &&
         disY <(rec1.height + rec2.height)/2){
                return true;

        }return false;

    }

    isGameOver(){
        if(this.bird.top === this.bird.maxY){
            // alert("game over");
            return true;//bird 碰到了 大地
        }
        for (let i = 0;i < this.pipeProducer.pairs.length; i++){
            const pair = this.pipeProducer.pairs[i];
            if(this.isHit(this.bird,pair.upPipe)||this.isHit(this.bird,pair.downPipe)){
            return true;//小鸟碰到了 馆子
            }
        }
        return false;
    }

    stop(){
        clearInterval(this.timer);
        this.timer = null;
        this.bird.stopSW();
        this.pipeProducer.stopProduce();
    }

    regEvent(){
        
        window.onkeydown = (e)=>{
            if(e.key === "Enter"){
                if(this.timer){
                    this.stop();
                }
                else{this.start();
                }  
            }else if(e.key === " "){
                this.bird.jump();
            }
        }
    }
    
    regEvent2(){
        element.addEventListener("touchstart",function () { 
            this.bird.jump();
        });
    }

// //定义touchstart的事件处理函数
//     function(e){
// 　　var touch = event.targetTouches[0]; //touches数组对象获得屏幕上所有的touch，取第一个touch
// 　　startPos = {x:touch.pageX,y:touch.pageY,time:+new Date}; //取第一个touch的坐标值
// 　　isScrolling = 0; //这个参数判断是垂直滚动还是水平滚动
// 　　this.slider.addEventListener('touchmove',this,false);
// 　　this.slider.addEventListener('touchend',this,false);
// }
}



var g = new Game();
g.regEvent();